package com.youme.section.shop

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.hyphenate.easeim.R
import com.youme.api.Callback
import com.youme.model.Food
import com.youme.model.FoodAdd
import com.youme.model.ProductDetail
import com.youme.model.Room
import com.youme.model.param.ParamAddFood
import com.youme.section.shop.adapter.DiancankehuAdapter
import com.youme.section.shop.adapter.FloatDecoration
import com.youme.section.shop.adapter.MenuLeftAdapter
import com.youme.section.shop.adapter.MenuRightAdapter
import com.youme.viewmodel.YouMeApiViewModel
import com.youme.widget.CenterLayoutManager
import com.ziwenl.meituandemo.bean.KehuBean
import com.ziwenl.meituandemo.bean.MenuTabBean
import kotlinx.android.synthetic.main.fragment_shop_details_menu.*
import kotlinx.android.synthetic.main.item_shop_details_menu_right_group.view.*
import kotlinx.coroutines.launch

class MenuFragment : Fragment(), ScrollableViewProvider, ShowCarListenerr, AddCaiListenerr {
    private var deskNum = ""
    private val mLeftData = mutableListOf<MenuTabBean>()
    private val mRightData = mutableListOf<Food>()
    private val deskIds = mutableListOf<Room>()
    private val sprnnerDate = arrayListOf<String>()
    private lateinit var mLeftAdapter: MenuLeftAdapter
    private lateinit var mLayoutControl: LayoutExpandControl
    private var mIsClickFold = false
    private var rectId = ""
    private var desktId = ""
    private var mRvState = RecyclerView.State()
    private lateinit var mLeftLayoutManager: CenterLayoutManager
    private lateinit var rightAdapter: MenuRightAdapter
    private lateinit var mFragmentIsShow: FragmentShowListenerr
    private lateinit var starAdapter: ArrayAdapter<String>
    private var foodList = mutableListOf<FoodAdd>()

    companion object {
        fun getInstance(
            layoutExpandControl: LayoutExpandControl
        ): MenuFragment {
            val fragment = MenuFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.setLayoutExpandControl(layoutExpandControl)
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_shop_details_menu, null)
    }

    public fun fragmentShow(listenerr: FragmentShowListenerr) {
        mFragmentIsShow = listenerr
    }

    public fun setAddListener2(listenerr: AddCaiListenerr) {
        rightAdapter.setAddListener2(listenerr)
    }

    public fun getCarListener(): MenuFragment {
        return this
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        rectId = activity?.intent?.getStringExtra("restId").toString()
        desktId = activity?.intent?.getStringExtra("deptId").toString()
        deskNum = activity?.intent?.getStringExtra("deskNum").toString()
        if (deskNum.isEmpty() || deskNum == null || deskNum.equals("null")) {
            sprnnerDate.add("请选择桌号")
        } else {
            sprnnerDate.add("桌号" + deskNum)
        }
        /* 初始化 */
        val layoutManager = LinearLayoutManager(activity)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        diancankehu.layoutManager = layoutManager

        val favoriteBeanList = arrayListOf<KehuBean>()
        favoriteBeanList.add(KehuBean("小潘潘"))
        favoriteBeanList.add(KehuBean("小阿婆"))
        favoriteBeanList.add(KehuBean("小老婆"))
        favoriteBeanList.add(KehuBean("小老婆"))
        favoriteBeanList.add(KehuBean("小老婆"))
        var adapter = DiancankehuAdapter(favoriteBeanList)
        diancankehu.adapter = adapter
        mLeftAdapter = MenuLeftAdapter(mLeftData)
        mLeftLayoutManager = CenterLayoutManager(context)
        rv_left.layoutManager = mLeftLayoutManager
        rv_left.adapter = mLeftAdapter
        rightAdapter = MenuRightAdapter(mRightData)
        rightAdapter.setAddListener(this)
        rightAdapter.setdestId(desktId)
        mFragmentIsShow.fragmentShow()
        rv_right.layoutManager = LinearLayoutManager(context)
        rv_right.adapter = rightAdapter
        //左边 RecyclerView item 点击事件监听
        mLeftAdapter.setCallback(object : MenuLeftAdapter.Callback {
            override fun onClickItem(position: Int) {
                for (i in 0 until mRightData.size) {
                    if (mLeftData[position].name == mRightData[i].categoryName) {
                        //未折叠时进行折叠
                        if (mLayoutControl.isExpanded()) {
                            mLayoutControl.fold()
                            mIsClickFold = true
                        }
                        if (rv_right.layoutParams.height != scrollView.height) {
                            rv_right.layoutParams.height = scrollView.height
                            rv_left.layoutParams.height = scrollView.height
                            rv_right.layoutParams = rv_right.layoutParams
                            rv_left.layoutParams = rv_left.layoutParams
                        }
                        //右边菜品 RecyclerView 将指定 item 滚动到可见第一条
                        (rv_right.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                            i,
                            0
                        )
                        mLeftAdapter.currentPosition = position
                        mLeftAdapter.notifyDataSetChanged()
                        break
                    }
                }
            }
        })

        //右边 RecyclerView 添加悬浮吸顶装饰
        rv_right.addItemDecoration(
            FloatDecoration(
                requireContext(),
                rv_right,
                R.layout.item_shop_details_menu_right_group,
                object : FloatDecoration.DecorationCallback {
                    override fun getDecorationFlag(position: Int): String {
                        //区分不同条目装饰 View 的 Flag
                        return mRightData[position].categoryName
                    }

                    override fun onBindView(decorationView: View, position: Int) {
                        //装饰 View 数据绑定
                        decorationView.tv_group_name.text = mRightData[position].categoryName
                    }
                })
        )

        //右边 RecyclerView 滚动监听
        rv_right.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //实现右边滚动联动左边 RecyclerView
                val position =
                    (rv_right.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                if (mLeftData[mLeftAdapter.currentPosition].name != mRightData[position].categoryName) {
                    for (i in 0 until mLeftData.size) {
                        if (mLeftData[i].name == mRightData[position].categoryName) {
                            mLeftAdapter.currentPosition = i
                            mLeftAdapter.notifyDataSetChanged()
                            mLeftLayoutManager.smoothScrollToPosition(
                                rv_left,
                                mRvState,
                                mLeftAdapter.currentPosition
                            )
                            break
                        }
                    }
                }
            }
        })
        //根据屏幕实际宽高设置两个recyclerView高度为固定值
        scrollView.post {
            rv_right.layoutParams.height = scrollView.height
            rv_left.layoutParams.height = scrollView.height
            rv_right.layoutParams = rv_right.layoutParams
            rv_left.layoutParams = rv_left.layoutParams
        }

        //记录是 rv_left 被触摸还是 rv_right 被触摸
        val onTouchListener = View.OnTouchListener { v, event ->
            when {
                event.action == MotionEvent.ACTION_DOWN && v.id == R.id.rv_right -> {
                    mIsTouchRvRight = true
                }
                event.action == MotionEvent.ACTION_UP && v.id == R.id.rv_right -> {
                    mIsTouchRvRight = false
                }
                event.action == MotionEvent.ACTION_DOWN && v.id == R.id.rv_left -> {
                    mIsTouchRvLeft = true
                }
                event.action == MotionEvent.ACTION_UP && v.id == R.id.rv_left -> {
                    mIsTouchRvLeft = false
                }
            }
            false
        }
        rv_right.setOnTouchListener(onTouchListener)
        rv_left.setOnTouchListener(onTouchListener)
        //scrollView 滚动监听
        scrollView.setOnScrollChangeListener(
            NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                val dy = scrollY - oldScrollY
                //上滑时，如果 bannerView 尚未被滚出屏幕，则不允许左右两个 RecyclerView 滚动 （通过 offsetChildrenVertical(dy) 实现两个 rv 未滚动的假象）
                if (dy > 0) {
                    if (scrollY < diancanrenyuan.height) {
                        if (mIsTouchRvRight) {
                            rv_right.offsetChildrenVertical(dy)
                        }
                        if (mIsTouchRvLeft) {
                            rv_left.offsetChildrenVertical(dy)
                        }
                    }
                }
            })
        initSpinner()
        //添加假数据
        getData()
    }

    private fun initSpinner() {
        starAdapter = activity?.let { ArrayAdapter<String>(it, android.R.layout.simple_spinner_item, sprnnerDate) }!!
        starAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = starAdapter
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (position > 0) {
                    desktId = deskIds[position - 1].id
                    rightAdapter.setdestId(desktId)
                }
            }
        }
    }

    private var mIsTouchRvRight = false
    private var mIsTouchRvLeft = false

    override fun getScrollableView(): View {
        if (rv_right.canScrollVertically(-1)) {
            return rv_right
        } else if (rv_left.canScrollVertically(-1)) {
            return rv_left
        } else {
            return scrollView
        }
    }

    override fun getRootScrollView(): View? {
        return scrollView
    }

    private fun getData() {
        val mViewModel = ViewModelProvider(this).get(YouMeApiViewModel::class.java)
        mViewModel.roomList(rectId, 1, object : Callback<List<Room>> {
            override fun onSuccess(value: List<Room>) {
                for (i in 0 until value.size) {
                    sprnnerDate.add("桌号：" + value[i].deskNum)
                    deskIds.addAll(value)
                }
            }

            override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                println(throwable)
                ToastUtils.show("请求失败,$errorCode,$errorMessage,$throwable")
            }
        })
        mViewModel.listProduct(rectId, object : Callback<ProductDetail> {
            override fun onSuccess(value: ProductDetail) {
                for (i in 0 until value.product.size) {
                    mLeftData.add(MenuTabBean(value.product[i].categoryName))
                }
                for (i in 0 until value.product.size) {
                    for (j in 0 until value.product[i].foods.size) {
                        mRightData.add(value.product[i].foods[j])
                    }
                }
                rv_left.adapter?.notifyDataSetChanged()
                rv_right.adapter?.notifyDataSetChanged()
            }

            override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                println(throwable)
                ToastUtils.show("请求失败,$errorCode,$errorMessage,$throwable")
            }
        })
    }

    private fun setLayoutExpandControl(layoutExpandControl: LayoutExpandControl) {
        mLayoutControl = layoutExpandControl
    }

    interface LayoutExpandControl {
        /**
         * 折叠布局
         */
        fun fold()

        /**
         * 布局是否展开
         */
        fun isExpanded(): Boolean
    }

    override fun jiesuan() {
        var price = 0.0
        for (i in 0 until foodList.size) {
            price = price + foodList[i].productPrice * foodList[i].productQuantity
        }
        val intent = Intent()
        intent.putExtra("price", price)
        activity?.let { intent.setClass(it, ChoujiangActivity().javaClass) }
        activity?.startActivity(intent)
    }

    override fun show() {
        if (foodList != null && foodList.size > 0) {
            ShopCarDialog.Builder(activity, foodList).show()
        } else {
            ToastUtils.show("请先点餐")
        }
    }

    override fun addCai(food: FoodAdd) {
        val mViewModel = ViewModelProvider(this).get(YouMeApiViewModel::class.java)
        val param = ParamAddFood(desktId, food.productId, 1)
        lifecycleScope.launch {
            mViewModel.addFood(param).apply {
                mViewModel.getList(desktId, object : Callback<List<FoodAdd>> {
                    override fun onSuccess(value: List<FoodAdd>) {
                        foodList.clear()
                        foodList.addAll(value)
                    }

                    override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                        println(throwable)
                        ToastUtils.show("请求失败,$errorCode,$errorMessage,$throwable")
                    }
                })
            }
        }
    }
}